<script>
import list from './list.vue'
import total from './total.vue'
import RegionCollection from '@/views/one-map/left-community-info/region-collection.vue'

export default {
  components: {
    list,
    total,
    RegionCollection,
  },
}
</script>
<script setup>
import {
  reactive,
  ref,
  computed,
  onMounted,
  nextTick,
  watch,
  getCurrentInstance,
} from 'vue'
import { getStatusInfo } from '@u/ststus-color'
import { importRegionBusiness, queryArea, queryTotal } from '@api/question'
import { cloneDeep } from 'lodash'
import SvgIcon from '@c/svg-icon/index.vue'
import { PERMISSIONS } from '@/common/user'
import { exportCommunityExcel } from '@/api/export'
import { Message, MessageBox } from 'element-ui'
import { downloadBlobFile, downloadFileWithBlob } from '@/utils/download'

const vm = getCurrentInstance()

const { currentUser } = vm?.proxy.$store.state.user

const expanded = ref(true)
const isStatic = ref(false)

const props = defineProps({
  legendArr: {
    type: Array,
    default: () => [],
  },
})

const canUploadShpTypeList = [
  'region-culture',
  'region-vacant',
  'region-business',
  'region-industry',
  'region-shop',
  'region-other',
]

let tempAreaInfo
let tempAreaIds

// 组件全局初始化user信息
const user = JSON.parse(localStorage.getItem('user')).user

const handleExpandedChange = () => {
  expanded.value = !expanded.value
}

const removeChildrenAtLevel = (tree, targetLevel) => {
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的level是否为目标level
    if (tree[i].level === targetLevel) {
      // 如果是的话，移除children属性
      delete tree[i].children
    }

    // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
    if (tree[i].children && tree[i].children.length > 0) {
      removeChildrenAtLevel(tree[i].children, targetLevel)
    }
  }

  return tree
}

const findNodeById = (tree, targetId) => {
  // console.log(tree, targetId)
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的ID是否为目标ID
    if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
      // 如果是的话，返回当前节点
      return tree[i]
    }

    // 如果当前节点有子节点，则递归在子节点中查找
    if (tree[i].children && tree[i].children.length > 0) {
      const foundNode = findNodeById(tree[i].children, targetId)
      // 如果在子节点中找到了，则返回找到的节点
      if (foundNode !== undefined) {
        return foundNode
      }
    }
  }

  // 如果在树中没有找到目标ID，则返回undefined
  return undefined
}

// 计算得到tabList;
const tabList = computed(() => {
  const level = user.roleLevel
  let list = [
    {
      id: 'community',
      name: '社区',
      type: 'total',
    },
    {
      id: 'residence',
      name: '小区',
      type: 'total',
    }
  ]
  // switch (level) {
  //   case 0:
  //   case 4:
  //   case 5:
  //     list = [
  //       // {
  //       //   id: 'region',
  //       //   name: '存量',
  //       //   type: 'list',
  //       // },
  //       {
  //         id: 'street',
  //         name: '街道',
  //         type: 'total',
  //       },
  //       {
  //         id: 'community',
  //         name: '社区',
  //         type: 'total',
  //       },
  //       {
  //         id: 'residence',
  //         name: '小区',
  //         type: 'total',
  //       },
  //       {
  //         id: 'satisfaction',
  //         name: '满意度调查',
  //         type: 'total',
  //       },
  //       {
  //         id: 'region-fill',
  //         name: '专项',
  //         type: 'region-collection',
  //       },
  //     ]
  //     break
  //   case 2:
  //     list = [
  //       {
  //         id: 'street',
  //         name: '街道',
  //         type: 'list',
  //       },
  //       {
  //         id: 'community',
  //         name: '社区',
  //         type: 'total',
  //       },
  //       {
  //         id: 'residence',
  //         name: '小区',
  //         type: 'total',
  //       },
  //       {
  //         id: 'satisfaction',
  //         name: '满意度调查',
  //         type: 'total',
  //       },
  //       {
  //         id: 'region-fill',
  //         name: '专项',
  //         type: 'region-collection',
  //       },
  //     ]
  //     break
  //   case 1:
  //     list = [
  //       {
  //         id: 'street',
  //         name: '街道',
  //         type: 'list',
  //       },
  //       {
  //         id: 'community',
  //         name: '社区',
  //         type: 'list',
  //       },
  //       {
  //         id: 'residence',
  //         name: '小区',
  //         type: 'total',
  //       },
  //       {
  //         id: 'satisfaction',
  //         name: '满意度调查',
  //         type: 'total',
  //       },
  //     ]
  //     break
  //   case 3:
  //     list = [
  //       {
  //         id: 'community',
  //         name: '社区',
  //         type: 'list',
  //       },
  //       {
  //         id: 'residence',
  //         name: '小区',
  //         type: 'list',
  //       },
  //       {
  //         id: 'satisfaction',
  //         name: '满意度调查',
  //         type: 'total',
  //       },
  //     ]
  //     break
  // }
  return list
})

const renderType = computed(() => {
  const type = tabList.value.find((item) => item.id === totalForm.type).type
  if (isStatic.value) {
    return 'list'
  } else {
    return type
  }
})

const areaIds = ref({
  regionId: '',
  streetId: '',
  communityId: '',
  districtId: '',
})

const regionType = ref('')

const handleBackClick = () => {
  areaInfo.value = cloneDeep(tempAreaInfo)
  areaIds.value = cloneDeep(tempAreaIds)
  listForm.status = ''
  nextTick(() => {
    tempAreaInfo = null
    tempAreaIds = null
    isStatic.value = false
  })
}

const areaForm = reactive({
  id: '',
  districtFlag: 'true',
})

onMounted(() => {
  getArea()
})

const casxaderProps = {
  value: 'pkid',
  label: 'areaName',
  checkStrictly: true,
}

const getArea = () => {
  queryArea(areaForm).then((res) => {
    if (res.success) {
      areaList.value = res.data
    }
  })
}

const areaList = ref([])

// 在统计表格当中，筛选有以下几种可能
// 市级账号看存量，最多可以level，1，也就是选择regionId,虽然没有意义
// 市级看街道，也是可以选择level到1，还是传regionId；
// 市级看社区，可以选level到2，传streetId，看小区同理；
// 区县账号不能看存量统计
// 区县看街道，可以选level到2，虽然没有意义；
// 区县看社区，可以选level到2，传streetId，看小区同理；
// 街道看社区不能看统计
// 看小区也只能传level到2，虽然没有意义；
// 社区看小区不能看统计
// 所以统计时最多只能level到2，也就是传streetId
// 列表最多可以筛选level到3，传communityId;

const options = computed(() => {
  const maxLevel = getMaxLevel()
  const tree = removeChildrenAtLevel(cloneDeep(areaList.value), maxLevel)
  const refId = user.refId
  const find = findNodeById(tree, refId)
  return find ? [find] : []
})

const getMaxLevel = () => {
  const type = renderType.value
  let level = 3
  if (type === 'total') {
    // 此时需要的参数最多可以到streetId；
    const resourceType = totalForm.type
    if (resourceType === 'street') {
      // 然后是街道
      // 可以选择街道
      // 也就是streetId
      level = 1
    } else if (resourceType === 'satisfaction') {
      level = 2
    } else {
      // 也就是communityId
      level = 2
    }
  } else if (type === 'region-collection') {
    level = 1
  } else {
    // 此时需要的参数最多可以到communityId；
    const resourceType = totalForm.type
    if (resourceType === 'region') {
      // 首先是存量资源
      // 可以选择区县
      // 也就是regionId
      level = 1
    } else if (resourceType === 'street') {
      // 然后是街道
      // 可以选择街道
      // 也就是streetId
      level = 2
    } else {
      // 也就是communityId
      level = 3
    }
  }
  return level
}

const areaInfo = ref(user.refId)

const totalForm = reactive({
  type: '',
})

totalForm.type = tabList.value[0].id

const streetName = ref('')

const listForm = reactive({
  status: '',
})

const statusOptions = [
  { label: '待提交', value: 0 },
  { label: '待审核', value: 2 },
  { label: '已通过', value: -1 },
  { label: '退回', value: 1 },
  { label: '未填写', value: -2 },
]
const componentRef = ref()
const handleClickTab = (item) => {
  regionType.value = ''
  if (item.name === 'satisfaction' || item.name === 'region-fill') {
    handleBackClick()
  }
  totalForm.type = item.name
  areaInfo.value = user.refId
  areaIds.value = {
    regionId: '',
    streetId: '',
    communityId: '',
    districtId: '',
  }
  listForm.status = ''
  if (item.name === 'region-fill') {
    if (user.roleLevel === 0 || user.roleLevel === 4) {
      areaInfo.value =
        options.value[0]?.children[0]?.children[0]?.pkid || '500191000000'
      areaIds.value.regionId =
        options.value[0]?.children[0]?.children[0]?.pkid || '500191000000'
    } else if (user.roleLevel === 5) {
      areaInfo.value = options.value[0]?.children[0]?.pkid || '500191000000'
      areaIds.value.regionId =
        options.value[0]?.children[0]?.pkid || '500191000000'
    } else {
      areaInfo.value = user.refId
      areaIds.value.regionId = user.refId
    }
  }
  nextTick(() => {
    componentRef.value.refresh()
  })
}

const handleChangeStatus = () => {
  nextTick(() => {
    componentRef.value.refresh()
  })
}

const handleChangeArea = () => {
  const areaCode = areaInfo.value[areaInfo.value.length - 1]
  const level = findNodeById(options.value, areaCode).level
  let obj = {
    regionId: '',
    communityId: '',
    streetId: '',
    districtId: '',
  }
  if (level === 1) {
    obj = {
      regionId: areaCode,
      streetId: '',
      communityId: '',
      districtId: '',
    }
  } else if (level === 2) {
    obj = {
      regionId: '',
      streetId: areaCode,
      communityId: '',
      districtId: '',
    }
  } else if (level === 3) {
    obj = {
      regionId: '',
      streetId: '',
      communityId: areaCode,
      districtId: '',
    }
  } else if (level === 5) {
    obj = {
      regionId: '',
      streetId: '',
      communityId: '',
      districtId: areaCode,
    }
  }
  areaIds.value = obj
  nextTick(() => {
    componentRef.value.refresh()
  })
  // console.log(areaInfo)
}

const handleClickTable = (row) => {
  if (renderType.value === 'region-collection') {
    tempAreaInfo = cloneDeep(areaInfo.value)
    tempAreaIds = cloneDeep(areaIds.value)
    regionType.value = row

    isStatic.value = true

    return
  }
  regionType.value = ''
  const { level, areaCode } = row
  // console.log(level, areaCode)
  let obj = {
    ...areaIds.value,
  }
  // console.log(obj)
  if (level === 3) {
    if (totalForm.type === 'residence') {
      // 可以对社区进行筛选
      // console.log(areaCode)
      obj = {
        regionId: '',
        streetId: '',
        communityId: areaCode,
      }
    } else {
      //
    }
  } else {
    if (level === 1) {
      obj = {
        regionId: areaCode,
        streetId: '',
        communityId: '',
      }
    } else if (level === 2) {
      obj = {
        regionId: '',
        streetId: areaCode,
        communityId: '',
      }
    }
    // console.log(areaCode)
  }
  tempAreaInfo = cloneDeep(areaInfo.value)
  tempAreaIds = cloneDeep(areaIds.value)
  areaIds.value = obj
  areaInfo.value = obj.communityId || obj.streetId || obj.regionId
  isStatic.value = true
}

const handleLeave = (activeName) => {
  return activeName !== 'satisfaction'
}

const getParams = () => {
  return areaIds.value
}

const checkList = ref([])
const legendShow = ref(false)

const changeLegend = (bool) => {
  legendShow.value = bool
}

watch(
  () => legendShow.value,
  async (val) => {
    if (val) {
      checkList.value = props.legendArr.map((i) => i.value)
    } else {
      checkList.value = []
    }
  }
)

watch(
  () => areaIds.value,
  () => {
    nextTick(() => {
      emit('changeArea')
    })
  },
  { deep: true }
)

const emit = defineEmits(['changeCheck', 'changeArea'])

const handleChangeCheck = () => {
  emit('changeCheck', checkList.value)
}

const tableDownloadLoading = ref(false)
const handleDownloadTable = (type) => {
  tableDownloadLoading.value = true
  const name = tabList.value.find((item) => item.id === totalForm.type).name
  if (type === 'total') {
    componentRef.value.download(name)
  } else {
    if (totalForm.type === 'satisfaction' || totalForm.type === 'residence') {
      Message.warning('满意度和小区暂不支持列表下载')
      tableDownloadLoading.value = false
      return
    }
    exportCommunityExcel(
      {
        ...areaIds.value,
        type: totalForm.type,
      },
      'status'
    )
      .then((res) => {
        downloadFileWithBlob(res, name + '填报列表.xlsx')
      })
      .finally(() => {
        tableDownloadLoading.value = false
      })
  }
}

const handleBackData = () => {
  MessageBox.confirm('是否确认批量退回勾选项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    componentRef.value.backData()
  })
}

const selectFile = () => {
  return new Promise((resolve) => {
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.click()
    fileInput.onchange = function (event) {
      const file = event.target.files[0]
      resolve({ message: true, event, file })
    }
  })
}

const uploadLoading = ref(false)
const handleUploadShp = () => {
  selectFile().then((res) => {
    if (res.message) {
      uploadLoading.value = true
      const file = res.file
      const formData = new FormData()
      formData.append('multipartFile', file)
      formData.append('type', regionType.value)
      formData.append('regionId', areaIds.value.regionId)
      importRegionBusiness(formData)
        .then((res) => {
          if (res.success) {
            Message.success('上传成功')
            componentRef.value.refresh()
          } else {
            Message.error(res.message || '上传失败')
          }
        })
        .finally(() => {
          uploadLoading.value = false
        })
    }
  })
}

const getCurrentCheckList = () => {
  return checkList.value
}

const setCheckList = (list) => {
  checkList.value = list
}

defineExpose({
  handleExpandedChange,
  getParams,
  changeLegend,
  getCurrentCheckList,
  setCheckList,
})
</script>

<template>
  <div class="community-info">
    <transition name="slide" mode="out-in" appear>
      <div class="panel" v-show="expanded">
        <div class="back" v-show="isStatic" @click="handleBackClick">
          <SvgIcon icon-class="goBack" title="返回" />
          <span class="text">统计</span>
        </div>
        <el-tabs v-model="totalForm.type" @tab-click="handleClickTab">
          <el-tab-pane
            v-for="item in tabList"
            :key="item.id"
            :label="item.name"
            :name="item.id"
          ></el-tab-pane>
        </el-tabs>
        <div class="filter-box">
          <el-cascader
            v-model="areaInfo"
            :options="options"
            :props="casxaderProps"
            class="area-cascader"
            :show-all-levels="false"
            @change="handleChangeArea"
          ></el-cascader>
          <template v-if="renderType === 'list'">
            <el-select
              clearable
              class="status-select"
              v-model="listForm.status"
              placeholder="状态"
              @change="handleChangeStatus"
            >
              <el-option
                v-for="(item, index) in statusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-tooltip
              placement="right"
              v-if="
                totalForm.type === 'region-fill' &&
                currentUser?.hasPermission(PERMISSIONS.一张图专项文件上传) &&
                canUploadShpTypeList.includes(regionType)
              "
            >
              <div slot="content">上传格式：2000坐标系<br />zip格式压缩包</div>
              <el-button
                type="text"
                :loading="uploadLoading"
                class="shp-upload"
                @click="handleUploadShp"
              >
                {{ currentUser?.getButtonName(PERMISSIONS.一张图专项文件上传) }}
              </el-button>
            </el-tooltip>
            <el-input
              v-if="false"
              clearable
              placeholder="街道名称"
              v-model="streetName"
              class="street-name-input"
            >
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <el-button
              v-if="
                currentUser?.hasPermission(PERMISSIONS.一张图批量退回) &&
                totalForm.type !== 'region-fill'
              "
              type="text"
              class="table-back"
              @click="handleBackData"
            >
              {{ currentUser?.getButtonName(PERMISSIONS.一张图批量退回) }}
            </el-button>
          </template>
          <template
            v-if="
              currentUser?.hasPermission(PERMISSIONS.一张图表格下载) &&
              renderType !== 'region-collection'
            "
          >
            <el-dropdown class="table-download" @command="handleDownloadTable">
              <el-button
                type="text"
                v-if="
                  !tableDownloadLoading &&
                  currentUser?.hasPermission(PERMISSIONS.一张图表格下载)
                "
              >
                {{ currentUser?.getButtonName(PERMISSIONS.一张图表格下载) }}
              </el-button>
              <el-button type="text" v-if="tableDownloadLoading">
                下载中...
              </el-button>
              <template #dropdown v-if="!tableDownloadLoading">
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="
                      totalForm.type !== 'satisfaction' &&
                      totalForm.type !== 'residence'
                    "
                    command="list"
                    >列表
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="renderType === 'total'"
                    command="total"
                    >统计
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
        <component
          :area-ids="areaIds"
          :type="totalForm.type"
          :status="listForm.status"
          :is="renderType"
          :regionType="regionType"
          ref="componentRef"
          @tabClick="handleClickTable"
          @downloaded="tableDownloadLoading = false"
        />
      </div>
    </transition>
    <div
      :class="['right-legend', expanded ? 'active' : '']"
      v-if="legendShow"
      @change="handleChangeCheck"
    >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in legendArr"
          :key="item.value"
          :label="item.value"
          :name="item.value"
          >{{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <!--    <div-->
    <!--      :class="['arrow-left', expanded ? 'active' : '']"-->
    <!--      @click="handleExpandedChange"-->
    <!--    >-->
    <!--      <i class="el-icon-arrow-left" v-if="expanded"></i>-->
    <!--      <i class="el-icon-arrow-right" v-else></i>-->
    <!--    </div>-->
  </div>
</template>

<style scoped lang="scss">
$panel-margin-left: 5px;
$panel-margin-right: 5px;
.community-info {
  position: absolute;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 12;
  display: flex;
  align-items: center;

  .panel {
    margin-left: $panel-margin-left;
    margin-right: $panel-margin-right;
    height: 100%;
    width: 430px;
    background: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.14) 0 2px;
    padding: 0 10px;
    box-sizing: border-box;
    position: relative;

    .back {
      position: absolute;
      right: 12px;
      top: 10px;
      cursor: pointer;
      z-index: 666;

      .text {
        margin-left: 6px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        font-size: 14px;
        color: #10a6dd;
      }
    }
  }

  .right-legend {
    overflow-y: auto;
    overflow-x: hidden;
    position: absolute;
    left: calc(430px + #{$panel-margin-left} + #{$panel-margin-right});
    bottom: 20px;
    width: 240px;
    height: 180px;
    background: #fff;
    box-shadow: rgba(0, 0, 0, 0.14) 0 2px;
    padding: 20px;
    box-sizing: border-box;
    z-index: 666;
    transform: translateX(-430px);
    transition: transform 0.4s ease-in-out;

    &.active {
      transform: translateX(0);
    }

    :deep(.el-checkbox-group) {
      display: flex;
      flex-direction: column;

      .el-checkbox {
        margin-bottom: 12px;
        margin-right: 0;
        display: flex;
        align-items: center;

        .el-checkbox__label {
          //换行
          white-space: normal;
        }
      }
    }
  }

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  .arrow-left {
    position: absolute;
    left: calc(430px + #{$panel-margin-left} + #{$panel-margin-right});
    width: 16px;
    height: 16px;
    color: #00c3ff;
    font-size: 16px;
    cursor: pointer;
    top: 50%;
    transform: translateY(-50%) translateX(-430px);
    transition: transform 0.4s ease-in-out;

    &.active {
      transform: translateX(0) translateY(-50%);
    }
  }

  .slide-enter-active,
  .slide-leave-active {
    transition: transform 0.4s ease-in-out;
  }

  .slide-enter,
  .slide-leave-to {
    transform: translateX(-430px);
  }

  .filter-box {
    display: flex;
    margin-top: 16px;
    margin-bottom: 16px;
    position: relative;

    :deep(.el-input) {
      height: 34px;

      .el-input__inner {
        height: 34px;
      }

      .el-input__icon {
        line-height: 34px !important;
      }
    }

    :deep(.area-cascader) {
      width: 100px;
      height: 34px;
      flex-shrink: 0;

      .el-input__inner {
        padding-right: 15px;
        border: none;
        color: #10a6dd;
      }

      .el-input__suffix-inner {
        margin-left: -30px;
        color: #10a6dd;
      }

      //.el-input__icon {
      //  line-height: 34px !important;
      //}
    }

    :deep(.status-select) {
      height: 34px;
      margin-right: 12px;

      .el-input__inner {
        width: 100px;
        background: #f9fbff;
        border-radius: 4px;
        border: 1px solid #e1ecf5;
      }
    }

    :deep(.street-name-input) {
      height: 34px;

      .el-input__inner {
        background: #f9fbff;
        border-radius: 4px 0px 0px 4px;
        border: 1px solid #e1ecf5;
      }
    }

    //:deep(.el-input) {
    //  .el-select {
    //    width: 100px;
    //  }
    //}

    .table-back {
      position: absolute;
      right: 56px;
      padding: 0;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .table-download {
      position: absolute;
      right: 16px;
      padding: 0;
      line-height: 34px;
    }

    .shp-upload {
      position: absolute;
      right: 56px;
    }
  }

  :deep(.el-pagination) {
    float: right;
  }

  :deep(.statistics-list) {
    height: calc(100% - 120px);

    .el-table {
      height: calc(100% - 40px);

      .el-table__row {
        cursor: pointer;
      }

      .el-table__body-wrapper {
        height: calc(100% - 48px);
        overflow-y: auto;
      }
    }
  }

  :deep(.statistics-total) {
    height: calc(100% - 100px);

    .el-table {
      height: calc(100% - 40px);

      .el-table__row {
        cursor: pointer;
      }

      .el-table__body-wrapper {
        height: calc(100% - 48px);
        overflow-y: auto;
      }
    }
  }

  :deep(.facility-collection) {
    height: calc(100% - 100px);
  }
}
</style>
